package com.example.mobile1931605084chy0604;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MusicService extends Service {
    MediaPlayer mediaPlayer;
    String TAG = "TAG";
    class ServiceBinder extends Binder{
        public MusicService getMusicService(){
            return MusicService.this;
        }
    }
    //定义绑定实现内部类，设计获得服务的方式
    public class MyBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.i(TAG, "onBind: ");
        return new ServiceBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: "+add(1,1));
        playMusic();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: ");
        stopMusic();
        super.onDestroy();
    }
    public int add(int a,int b){
        return a + b;
    }
    public void playMusic(){
        Log.i(TAG, "playMusic: ");
        mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.oldboy);
        mediaPlayer.start();
    }
    public void pauseMusic(){
        Log.i(TAG, "pauseMusic: ");
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
    }
    public void replayMusic(){
        Log.i(TAG, "reolayMusic: ");
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
            mediaPlayer.seekTo(0);
            mediaPlayer.start();
        }
    }
    public void stopMusic(){
        Log.i(TAG, "stopMusic: ");
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
